package com.jiezuo.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiezuo.auth.entity.Permission;
import com.jiezuo.auth.entity.PermissionApi;
import com.jiezuo.auth.entity.Role;
import com.jiezuo.auth.entity.RolePermission;
import com.jiezuo.auth.service.PermissionApiService;
import com.jiezuo.auth.service.RolePermissionService;
import com.jiezuo.auth.service.RoleService;
import com.jiezuo.common.base.BaseController;
import com.jiezuo.common.constant.SysConstant;
import com.jiezuo.common.enums.ResultEnums;
import com.jiezuo.common.exception.BusinessRuntimeException;
import com.jiezuo.common.util.ResultUtil;
import com.jiezuo.common.util.StringUtil;
import com.jiezuo.common.util.VerifyUtil;
import com.jiezuo.common.vo.Result;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @description 角色权限模块
 * @author 庞留杰
 * @date 2020/09/02 19:07
 * @version V1.0
 **/
@Slf4j
@Transactional
@RequestMapping("/rolePermission")
@RestController
//角色权限模块", tags = {"角色权限模块接口"})
public class RolePermissionController extends BaseController {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private RolePermissionService service;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionApiService permissionApiService;

    //保存", notes = "保存")
    @PostMapping("/update")
    public Result update(@RequestBody RolePermission rolePermission) {
        //非空校验
        VerifyUtil.notEmpty("角色ID", rolePermission.getRole_id());
        List<Permission> permissions = rolePermission.getMenus();

        // 保存前清空
        QueryWrapper<RolePermission> query = new QueryWrapper();
        query.eq("role_id", rolePermission.getRole_id());
        service.remove(query);

        List<RolePermission> rps = new ArrayList<>();
        for (Permission p : permissions) {
            RolePermission rp = new RolePermission();
            rp.setRole_id(rolePermission.getRole_id());
            rp.setPermission_id(p.getId());
            rps.add(rp);
        }
        boolean boo = service.saveBatch(rps);
        // 清理redis数据
        Set<String> keys = redisTemplate.keys(SysConstant.REDIS_DATA_AUTHORITY + "*");
        Long delete = redisTemplate.delete(keys);
        if (boo) {
            return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
        } else {
            return new ResultUtil().setErrorMsg(ResultEnums.FAIL.getReasonPhraseCN());
        }
    }

    @GetMapping("/findRolePermission")
    public Result<RolePermission> findRolePermission(@ModelAttribute RolePermission rolePermission) {
        VerifyUtil.notEmpty("资源ID", rolePermission.getPermission_id());
        VerifyUtil.notEmpty("角色ID", rolePermission.getRole_id());
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper();
        queryWrapper.eq("permission_id", rolePermission.getPermission_id());
        queryWrapper.eq("role_id", rolePermission.getRole_id());
        List<RolePermission> list = service.list(queryWrapper);
        Role role = roleService.getById(rolePermission.getRole_id());
        RolePermission rp = new RolePermission();
        if (list.size() > 0) {
            BeanUtils.copyProperties(list.get(0), rp);
            if (!StringUtil.isNotEmpty(rp.getData_authority_level())) {
                RolePermission rp1 = new RolePermission();
                rp1.setId(rp.getId());
                rp1.setRole_id(rolePermission.getRole_id());
                rp1.setPermission_id(rolePermission.getPermission_id());
                rp1.setData_authority_level(role.getData_authority_level());
                rp1.setRole_depart(role.getRole_depart());
                BeanUtils.copyProperties(rp1, rp);
            }
        } else {
            RolePermission rp1 = new RolePermission();
            rp1.setRole_id(rolePermission.getRole_id());
            rp1.setPermission_id(rolePermission.getPermission_id());
            rp1.setData_authority_level(role.getData_authority_level());
            rp1.setRole_depart(role.getRole_depart());
            BeanUtils.copyProperties(rp1, rp);
        }
        return new ResultUtil<RolePermission>().setData(rp);
    }

    //添加或修改")
    @PostMapping("/addOrUpdate")
    public Result addOrUpdate(@RequestBody RolePermission rolePermission) {
        VerifyUtil.notEmpty("权限ID", rolePermission.getPermission_id());
        QueryWrapper<PermissionApi> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        queryWrapper.eq("permission_id", rolePermission.getPermission_id());
        List<PermissionApi> list = permissionApiService.list(queryWrapper);
        if (list.size() == 0) {
            throw new BusinessRuntimeException("当前菜单没有配置列表接口，不允许设置权限等级");
        }
        boolean boo = service.saveOrUpdate(rolePermission);
        // 清理redis数据
        Set<String> keys = redisTemplate.keys(SysConstant.REDIS_DATA_AUTHORITY + "*");
        Long delete = redisTemplate.delete(keys);
        if (boo) {
            return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
        } else {
            return new ResultUtil().setErrorMsg(ResultEnums.FAIL.getReasonPhraseCN());
        }
    }

}
